import {Footer} from '@/components';
import {
  AlipayCircleOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import {Helmet, history, useModel} from '@umijs/max';
import {Alert, message, Tabs} from 'antd';
import {createStyles} from 'antd-style';
import React, {useState, useEffect} from 'react';
import {flushSync} from 'react-dom';
import {getCodeUsingGet, loginUsingPost, reGetCodeUsingPost} from "@/services/easyapi/eUserCenter";
import {values} from "lodash";

const useStyles = createStyles(({token}) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});
const ActionIcons = () => {
  const {styles} = useStyles();
  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action}/>
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action}/>
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action}/>
    </>
  );
};
const Lang = () => {
  const {styles} = useStyles();
  return;
};
const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};
const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [captcha, setCaptcha] = useState<API.Captcha>();
  const [image, setImage] = useState<string>();
  const [type, setType] = useState<string>('account');
  const {initialState, setInitialState} = useModel('@@initialState');
  const {styles} = useStyles();
  const getCaptcha = async () => {
    await getCodeUsingGet().then(res => {
      setCaptcha(res.data)
      //@ts-ignore
      setImage("data:image/png;base64," + res.data.image)
      //@ts-ignore
      localStorage.setItem("uuid",res.data.uuid)
    })
  }
  const refishCaptcha = async ()=>{
    const uuid = localStorage.getItem("uuid");
    await reGetCaptcha({
      ...values,
      //@ts-ignore
      "uuid": uuid
    })
  }

  const reGetCaptcha = async (values: API.Captcha) => {
    await reGetCodeUsingPost(values).then(res => {
      setCaptcha(res.data)
      //@ts-ignore
      setImage("data:image/png;base64," + res.data.image)
    })
  }
  useEffect(() => {
    const uuid = localStorage.getItem("uuid");
    if (uuid!=null){
      reGetCaptcha({
        ...values,
        "uuid":uuid
      })
      console.log("aa-->{}",uuid)
    } else {
      getCaptcha()
    }
  }, []);
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const handleSubmit = async (values: API.UserLoginParam) => {
    try {
      const msg = await loginUsingPost({
        ...values,
        //@ts-ignore
        uuid:localStorage.getItem("uuid")
      });
      if (msg.code === 200) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      //@ts-ignore
      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  const {status, type: loginType} = userLoginState;
  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'登录'}
        </title>
      </Helmet>
      {/*@ts-ignore*/}
      <Lang/>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg"/>}
          title="Easy API"
          subTitle={'Easy API 高效安全的一体化数据服务平台'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.UserLoginParam);
          }}
        >
          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined style={{color: "#319cff"}}/>,
                }}
                placeholder={'用户账户'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                  {
                    pattern:/^[a-zA-Z0-9][a-zA-Z0-9_]{3,15}$/,
                    message:'账户由数字和字母组成，且长度为4-16位'
                  }
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined style={{color: "#319cff"}}/>,
                }}
                placeholder={'用户密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                  {
                    pattern:/^[a-zA-Z]\w{7,15}$/,
                    message:'密码由母开头，长度在8~16之间，只能包含字母、数字和下划线'
                  }
                ]}
              />
              <ProFormText
                name="code"
                fieldProps={{
                  size: 'large',
                  prefix: <SafetyCertificateOutlined style={{color: "#319cff"}}/>,
                  suffix: <img
                    style={{width: '100%', height: '25px', verticalAlign: 'initial', padding: '-1px 0px 0px 20px'}}
                    src={image} alt="图片走丢啦~" onClick={refishCaptcha}/>
                }}
                placeholder={'验证码'}
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 60,
            }}
          >
            <a
              style={{
                float: 'left',
              }}
            >
              忘记密码 ?
            </a>
            <a
              style={{
                float: 'right',
              }}
              href={'/user/register'}
            >
              没有账号 ?
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};
export default Login;
